import React from 'react';
import {browserHistory} from 'react-router';
import $ from 'jquery';
import { Form, Button, Input, message, Modal } from 'antd';
import config from '../../../config/config';
const FormItem = Form.Item;
const allRouter=config.router;
const token = sessionStorage.getItem('token');
class AddPatientOrigin extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            hasNamed:false,//验证重名
        }
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {
    }
    componentDidMount() {
        //判断是点击新增还是编辑跳转，如果是编辑，则请求数据显示在表单中
        if(this.props.params.patientOriginId !== "0"){
            let url=allRouter.patientOrigin+'/source/one/'+this.props.params.patientOriginId;
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    if(data.code===200){
                        this.props.form.setFieldsValue({
                            patientOriginName:data.source.name,
                        });
                    }else{
                        console.log("获取患者来源名称出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        }
    }
    //点击确定，保存患者来源数据
    saveData(){
        this.props.form.validateFields((err,values)=> {
            //发送Ajax请求，post，
            if(err){return}
            if(this.state.hasNamed){
                message.error('该患者来源名称已经存在!',1);
                return;
            }
            let url=allRouter.patientOrigin+'/source/save';
            //如果表单值为空，则return
            if(!values.patientOriginName){
                return;
            }
            //即是编辑状态
            if(this.props.params.patientOriginId !== "0"){
                let url=allRouter.patientOrigin+'/source/update';
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        id:this.props.params.patientOriginId,
                        name:values.patientOriginName
                    },
                    success:data=>{
                        if(data.code===200){
                            message.info('更改名称成功',);
                            browserHistory.push('/patientOriginManage');
                        }else if(data.code==201){
                            // message.error('患者来源名称已存在，请修改');
                            this.props.form.setFields({
                                patientOriginName: { value: values.patientOriginName,errors: [new Error('患者来源名称已存在，请修改')] }
                            })
                        }else{
                            message.info('更改状态错误');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
                return;
            }
            //即是新增状态
            $.ajax({
                url:url,
                type: "POST",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data:{
                    name:values.patientOriginName,
                    state:'启用',
                },
                success:data=>{
                    if(data.code===200){
                        message.info('增加成功',);
                        browserHistory.push('patientOriginManage');
                    }else if(data.code==201){
                        // message.error('患者来源名称已存在，请修改');
                        this.props.form.setFields({
                            patientOriginName: { value: values.patientOriginName,errors: [new Error('患者来源名称已存在，请修改')] }
                        })
                    }else{
                        message.info('增加失败');
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回患者来源列表页面吗？',
            cancelText:'取消',
            okText:'确定',
            onCancel:()=>{},
            onOk:()=>{
                browserHistory.push('/patientOriginManage');
            }
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div className='container'>
                <div className='add-department-box'>
                    <div className="show-template">
                        <span>*{this.props.params.patientOriginId != "0"?"编辑":"新增"}患者来源名称</span>
                    </div>
                    <div className='storeRow' >
                        <FormItem {...{ labelCol: { span: 3 }, wrapperCol: { span: 18 } }} label="患者来源名称" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('patientOriginName', {
                                rules: [
                                    {required: true, message: '患者来源名称不能为空',},
                                    { max: 15, message: '最多不能超过15个字' },
                                    { pattern: /^([\u4e00-\u9fa5]|[a-zA-Z0-9]){1,15}$/, message: '请输入中文或英文或数字'}
                                ],

                            })(
                                <Input placeholder="患者来源名称" />
                            )}
                        </FormItem>
                    </div>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>
                </div>
            </div>
        )
    }
}
const AddPatientOriginForm = Form.create()(AddPatientOrigin);
export default AddPatientOriginForm;